// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import Fk
import Fk.Components.LunarLTK
import Fk.Pages.LunarLTK
import Fk.Components.Common
import Qt5Compat.GraphicalEffects
import "choiceBoxComponents" as ChoiceComponents

ChoiceComponents.ChoiceBg {
  id: root
  
  property var card_names: []
  property var all_names: []
  property string prompt : ""
  property string result : ""
  property alias cardDetail: cardDetail

  function processMatrixRowLengthCompact(matrix) {
    /*
      内容由 AI 生成，请仔细甄别：
      输入一个二维数组，取每行元素数组成一个一维数组1，
      对其中的元素{若小于5则取原值，大于4且小于9则取3，否则取其算数平方根（向下取整）}构成一个一维数组2并取其中的最大值，
      对一维数组1中每个元素{除以该值（向上取整）并乘以该值}求和，对该和取算数平方根（向下取整），
      若得到的值大于5，则返回6，小于4，则取其与一维数组2中所有数的最大值。
    */
    const arr1 = matrix.map(row => row?.length || 0);
    if (!arr1.length) return 0;
    
    const arr2 = arr1.map(v => v < 5 ? v : v < 9 ? 3 : Math.floor(Math.sqrt(v)));
    const max2 = Math.max(...arr2);
    if (!max2 || max2 === 0) return 0;
    
    const sum = arr1.reduce((t, v) => t + Math.ceil(v / max2) * max2, 0);
    const sqrtSum = Math.floor(Math.sqrt(sum));
    
    return sqrtSum > 5 ? 6 : sqrtSum < 4 ? Math.max(sqrtSum, Math.max(...arr2)) : sqrtSum;
  }

  property int lines: processMatrixRowLengthCompact(all_names)

  title.text: Util.processPrompt(prompt)
  width: {
    return Math.min(Math.max(Math.ceil(all_names[0]?.length / lines) * 100, 100), 700)
  }
  height: lines * 50 + 20 + 40

  Item {
    id: cardDetail
    width: 200
    height: Math.max(parent.height, 24 + cardImg.height + detailText.height)
    anchors.left: parent.right
    anchors.top: parent.top
    visible: false

    property string cardImgName: "slash"

    BorderImage {
      source: Cpp.path + "/packages/lunarltk-qsgs-ui/image/selfArea/choiceBox/card-detail-bg.png"
      border.left: 5
      border.right: 5
      border.top: 5
      border.bottom: 5
      anchors.fill: parent
    }

    CardItem {
      id: cardImg
      cid: 0
      name: parent.cardImgName
      suit: ""
      number: 0
      autoBack: false
      cardScale: 0.8
      anchors.left: parent.left
      anchors.leftMargin: 8
      anchors.top: parent.top
      anchors.topMargin: 8
    }

    Text {
      id: detailName
      text: Lua.tr(parent.cardImgName)
      font.pixelSize: 18
      font.family: "SimSun"
      font.bold: true
      wrapMode: Text.WordWrap
      textFormat: TextEdit.RichText
      color: '#ffefb7'
      anchors.right: parent.right
      anchors.rightMargin: 8
      anchors.left: cardImg.right
      anchors.leftMargin: 8
      anchors.top: parent.top
      anchors.topMargin: 16
    }

    Text {
      id: detailText
      text: "<b>" + Lua.tr(":" + parent.cardImgName) + "</b>"
      font.pixelSize: 10
      font.family: "SimSun"
      wrapMode: Text.WordWrap
      textFormat: TextEdit.RichText
      color: detailName.color
      anchors.right: parent.right
      anchors.rightMargin: 8
      anchors.left: parent.left
      anchors.leftMargin: 8
      anchors.top: cardImg.bottom
      anchors.topMargin: 8
    }
  }

  Flickable {
    id : flickableContainer

    // 内容宽度大于可视区域宽度以启用水平滚动
    contentWidth: cardArea.implicitWidth
    contentHeight: cardArea.implicitHeight  // 内容高度与可视区域高度相同，禁用垂直滚动

    anchors.topMargin: Math.max(40, (parent.height - contentHeight) / 2)
    anchors.leftMargin: Math.max(10, (parent.width - contentWidth) / 2)
    anchors.rightMargin: 10
    anchors.bottomMargin: 20
    anchors.fill: parent

    // 只允许水平滚动
    flickableDirection: Flickable.HorizontalFlick
    // 根据内容宽度决定是否可交互
    interactive: contentWidth > parent.width - 20
    // 启用裁剪
    clip: true

    Row {
      id: cardArea
      anchors.centerIn: parent
      spacing: 20

      Repeater {
        id: areaRepeater
        model: all_names
        
        delegate : GridLayout {
          id: gridLayout
          columns: Math.ceil(modelData.length / lines)
          columnSpacing : 10
          rowSpacing : 10
          
          Repeater {
            id: cardRepeater
            model: modelData

            delegate: ChoiceComponents.CardNameItem {
              id: cardItem
              itemData: modelData
              card_names: root.card_names
              enabled: root.card_names.includes(itemData)

              onClicked: {
                result = itemData;
                root.close();
              }

              onHoveredChanged: {
                const detail = root.cardDetail;
                if (hovered === true) {
                  detail.cardImgName = modelData;
                  detail.visible = true;
                } else {
                  // detail.visible = false;
                }
              }
            }
          }
          
        }

      }
    }

    
  }

}
